import Taro from '@tarojs/taro'

import { cosEnvConfig } from '@/common/constants'
import { credentialService } from '@/common/service/cos'
import { fileNamePath } from '@/common/utils/tools'

import { Directory, File } from './type'

const COS = require('@/common/sdk/cos/cos-wx-sdk-v5.min.js')

// 初始化实例
export const cos = new COS({
  getAuthorization: async (_options, callback) => {
    const result = await credentialService()
    callback({
      ...result
    })
  }
})

/**
 * 上传单个图片
 * @param param0 name: 文件名，path: 文件路径，suffix: 文件后缀, bucketName: 存储桶名
 * @returns Promise 图片链接url
 */
export const putObject = async ({ path, suffix = 'png', directory }: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    cos.putObject(
      {
        Bucket: cosEnvConfig.Bucket /* 填写自己的 bucket，必须字段 */,
        Region: cosEnvConfig.Region /* 存储桶所在地域，必须字段 */,
        Key: fileNamePath(suffix, directory) /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */,
        FilePath: path
      },
      (err, data) => {
        if (err) {
          reject(err)
        } else {
          resolve(`https://${data.Location}`)
        }
      }
    )
  })
}

/**
 * 批量上传图片
 * @param files 多个文件对象
 * @param directory 目录名：avatar/dynamic
 */
export const uploadFiles = async (files: File[], directory: Directory) => {
  Taro.showLoading({
    title: '加载中'
  })
  const fileList = files.map(function (file) {
    return Object.assign(file, {
      Bucket: cosEnvConfig.Bucket,
      Region: cosEnvConfig.Region,
      Key: fileNamePath(file.suffix, directory),
      FilePath: file.path
    })
  })
  return new Promise<Array<{ url: string }>>((resolve, reject) => {
    cos.uploadFiles(
      {
        files: fileList,
        SliceSize: 1024 * 1024 * 3, // 文件大于3mb自动使用分块上传
        onProgress: function (info) {
          const percent = (info.percent * 10000) / 100
          const speed = ((info.speed / 1024 / 1024) * 100) / 100
          console.log('进度：' + percent + '%; 速度：' + speed + 'Mb/s;')
        }
      },
      (err, data) => {
        console.log('%c [ err ]-74', 'font-size:13px; background:pink; color:#bf2c9f;', err)
        Taro.hideLoading()
        if (err) {
          return reject(err)
        }
        return resolve(data.files.map(item => ({ url: `https://${item.data.Location}` })))
      }
    )
  })
}
